package ro.peoplecentric.ctc.faces.phase;

import java.util.List;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

/**
 * Allow messages from validation annotations like Pattern, Max, Min to contain a i18n keys.
 * All validation messages will pass through Application's ResourceBundle for resolving keys if there are any. 
 * 
 * @author pguzun
 */
public class ValidationMessagePhaseListener implements PhaseListener {
	private static final long serialVersionUID = 1L;
	private static final String RESOURCE_NAME = "msgs";

	@Override
	public void afterPhase(PhaseEvent event) {
		FacesContext facesContext = event.getFacesContext();
		i18nMessages(facesContext);
	}

	private void i18nMessages(FacesContext facesContext) {
		List<FacesMessage> messageList = facesContext.getMessageList();
		if (!messageList.isEmpty()) {
			ResourceBundle resourceBundle = facesContext.getApplication().getResourceBundle(facesContext, RESOURCE_NAME);
			for (FacesMessage message : messageList) {				
				String summary = resourceBundle.getString(message.getSummary());
				String detail = resourceBundle.getString(message.getDetail());				
				message.setSummary(summary);
				message.setDetail(detail);
			}
		}
	}


	@Override
	public void beforePhase(PhaseEvent event) {
		// empty
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.PROCESS_VALIDATIONS;
	}

}
